/*
 * @Descripttion: 团队管理即为平台端的单位成员
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-11-02 14:26:03
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2023-02-20 10:43:43
 */
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
    showMsg
} from '../../../../utils/config.js'
import {
    reqOrgUserList,
    reqOrgApprovalList,
    reqOrgUserDel,
    reqOrgApprovalEdit,
    reqOrgTurnOver,
    reqOrgExit,
    reqOrgList
} from '../../../../request/api'
const exitLoginBehavior = require('../../behaviors/personal/exitLogin.js')
Page({
    behaviors: [exitLoginBehavior],
    data: {
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        isTeamManager: '', //是否为此单位管理员
        currentTab: 0, //隔离中/解除隔离
        tabList: [{
            id: 0,
            name: '我的团队'
        }, ],
        // 搜索开始
        active: false,
        searchType: 'username',
        searchValue: '',
        // 搜索结束
        dataList: [],
        page: 1,
        isNextPage: true,
        triggered: false,
        srcDefaultAvatar1: '/statics/images/personal-center/touxiang1.png',
        srcDefaultAvatar2: '/statics/images/personal-center/touxiang2.png',
        srcDefaultAvatar3: '/statics/images/personal-center/touxiang3.png',
        srcDefaultAvatar4: '/statics/images/personal-center/touxiang4.png',
        srcDefaultAvatar5: '/statics/images/personal-center/touxiang5.png',
        srcDefaultAvatar6: '/statics/images/personal-center/touxiang6.png',
        srcUsername: '/statics/images/personal-center/default_avatar.png',
        // 更多操作开始
        showMoreActions: false, //是否展示更多操作
        listItemInfo: {}, //点击更多时列表一项信息
        // 更多操作结束
        // 审批开始
        showStatus: false,
        statusApprove: 1,
        statusApproveText: "待审批",
        statusList: [{
            id: 1,
            text: '待审批',
        }, {
            id: 2,
            text: '通过',
        }, {
            id: 3,
            text: '拒绝',
        }, ],
        dataList1: [],
        page1: 1,
        isNextPage1: true,
        triggered1: false,
        showMoreActions1: false,
        listItemInfo1: {},
        // 审批结束

        // teamTotal: 0,
        showRole: false,
        roleList: [{
            id: '1',
            text: "管理员"
        }, {
            id: '2',
            text: "消防安全专员"
        }, {
            id: '3',
            text: "消防安全负责人"
        }, {
            id: '4',
            text: "消防监管人"
        }, {
            id: '5',
            text: "专职消防安全管理人"
        }, {
            id: '6',
            text: "楼(建筑)长"
        }, {
            id: '7',
            text: "维保人员"
        }, ],
        showRole2: false,
        roleList2: [{
            id: '2',
            text: "消防安全专员"
        }, {
            id: '3',
            text: "消防安全负责人"
        }, {
            id: '4',
            text: "消防监管人"
        }, {
            id: '5',
            text: "专职消防安全管理人"
        }, {
            id: '6',
            text: "楼(建筑)长"
        }, {
            id: '7',
            text: "维保人员"
        }],
        isShowBtn: false
    },
    onLoad(e) {
        // console.log(e);
        // this.setData({
        //     teamTotal: e.teamTotal
        // })
        this.getOrgListInit()

    },
    onShow() {
        this.getAddTab1()
        this.getInitDataList()
        this.getInitDataList1()
    },
    // 获取组织列表
    async getOrgListInit() {
        let params = {
            tenantId: app.globalData.tenantId,
            userId: app.globalData.userId,
            roleName: app.globalData.rolename,
            parentId: ""
        }
        const res = await reqOrgList(this.data.page, 50, params)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        if (rows.length) {
            let filterOrg = rows.filter(item => item.id == app.globalData.orgId)
            console.log(filterOrg, "filterOrg")
            this.setData({
                isShowBtn: filterOrg.length ? true : false
            })
        }
    },
    // 如果是组织管理员，则加入审批tab
    getAddTab1() {
        let params = {
            id: 1,
            name: '审批'
        }
        let {
            tabList
        } = this.data
        let {
            isTeamManager
        } = app.globalData
        console.log(app.globalData.isTeamManager);
        this.setData({
            isTeamManager
        })
        if (tabList.length >= 2) return
        if (isTeamManager) {
            tabList.push(params)
            this.setData({
                tabList
            })
        }
    },
    /**
     * @name:   点击切换 
     * @msg:    1、赋值current 
     * @param {*} e
     * @return {*}
     */
    swichNav(e) {
        let {
            current
        } = e.currentTarget.dataset
        this.setData({
            currentTab: current
        })
        // this.getInitDataList()
    },
    /**
     * @name: 滑动切换
     * @msg:  1、赋值curren
     * @param {*} e
     * @return {*}
     */
    bindChangeTab(e) {
        let {
            current
        } = e.detail
        this.setData({
            currentTab: current
        })
        if (current === 0) {
            this.getInitDataList()
        } else {
            this.getInitDataList1()
        }
    },
    // 搜索开始
    // 点击切换用户名/手机号
    toggleSearchClick() {
        this.setData({
            active: !this.data.active
        })
    },
    // 切换搜索条件
    itemClick(e) {
        let {
            type
        } = e.currentTarget.dataset
        this.setData({
            searchType: type,
            active: !this.data.active
        })
    },
    // 获取输入值
    searchValueChange(e) {
        this.setData({
            searchValue: e.detail.value
        })
    },
    // 清除输入值
    clearUsername() {
        this.setData({
            searchValue: ''
        })
        this.getInitDataList()
    },
    // 点击搜索成员
    async searchClick() {
        let {
            searchValue
        } = this.data
        if (!searchValue) return showMsg("请先输入搜索信息")
        this.getInitDataList()
    },
    // 搜索结束
    async getDataList() {
        let username = ''
        let mobile = ''
        let {
            searchValue,
            searchType
        } = this.data
        if (searchType === 'username') {
            username = searchValue
            mobile = ''
        } else {
            username = ''
            mobile = searchValue
        }
        let params = {
            orgId: app.globalData.orgId == 1 ? '' : app.globalData.orgId,
            username,
            mobile,
            userId: app.globalData.userId,
            roleName: app.globalData.rolename,
        }
        const res = await reqOrgUserList(this.data.page, 12, params)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        console.log(rows);
        // console.log(wx.getStorageSync('mobile'));
        // 判断是否 是此单位管理员 第二次进入才生效
        if (rows.length > 1) {
            if (rows[0].mobile == wx.getStorageSync('mobile')) {
                app.globalData.isTeamManager = true //role为1：单位管理员 role为2：消防安全员
                wx.setStorageSync('isTeamManager', true);
            }
        }
        if (this.data.page === 1) {
            this.setData({
                dataList: rows,
                isNextPage: true
            })
        } else if (this.data.page > 1 && (rows && rows.length)) {
            this.setData({
                dataList: this.data.dataList.concat(rows),
                isNextPage: true
            })
        } else if (this.data.page > 1 && (!rows || !rows.length)) {
            showMsg('已经到底啦~')
            this.setData({
                isNextPage: false
            })
        }
    },
    // 滚动到底部触发
    lower() {
        if (!this.data.isNextPage) return
        this.setData({
            page: this.data.page + 1,
        })
        this.getDataList()
    },
    // 下拉刷新
    async onRefresh() {
        this.setData({
            dataList: [],
            page: 1,
            isNextPage: true,
            triggered: true,
        })
        await this.getDataList()
        this.setData({
            triggered: false,
        })
    },
    // 输入框搜索
    searchChange(e) {
        this.data.searchValue = validateEmoji(e.detail.replace(/\s+/g, ''))
        this.setData({
            searchValue: this.data.searchValue,
            page: 1,
            isNextPage: true
        })
        clearTimeout(this.data.timer)
        this.data.timer = setTimeout(() => {
            this.getDataList()
        }, 500)
    },
    // 操作列表后回到最初状态
    getInitDataList() {
        this.setData({
            page: 1,
            isNextPage: true,
            dataList: []
        })
        this.getDataList()
    },

    // 点击更多操作
    clickMore(e) {
        let {
            item
        } = e.currentTarget.dataset
        this.setData({
            listItemInfo: item,
            showMoreActions: true
        })
    },
    // 点击xx
    closeMoreActions() {
        this.unShowMoreActions()
    },
    // 隐藏更多操作弹窗
    unShowMoreActions() {
        this.setData({
            showMoreActions: false
        })
    },
    clickDelete(e) {
        this.setData({
            listItemInfo: e.currentTarget.dataset.item
        })
        Dialog.confirm({
                title: '温馨提示',
                message: `此操作将删除成员 ${this.data.listItemInfo.username}，是否继续？`,
            })
            .then(async () => {
                const res = await reqOrgUserDel({
                    idList: [this.data.listItemInfo.id]
                })
                this.unShowMoreActions()
                if (res.code != 20000) return showMsg(res.message);
                this.getInitDataList()
                showMsg("删除成功")
            })
            .catch(() => {});
    },
    // 隐藏岗位
    roleClose() {
        this.setData({
            showRole: false
        })
    },
    // 设置岗位
    clickExChange() {
        let {
            listItemInfo
        } = this.data
        console.log(listItemInfo);
        this.setData({
            showRole: true
        })
        // Dialog.confirm({
        //         title: '温馨提示',
        //         message: `此操作将移交管理权限给 ${listItemInfo.username}，是否继续？`,
        //     })
        //     .then(async () => {
        //         const res = await reqOrgTurnOver({
        //             orgId: app.globalData.orgId ==1?'':app.globalData.orgId,
        //             userId: listItemInfo.userId,
        //             role:1
        //         })
        //         this.unShowMoreActions()
        //         if (res.code != 20000) return showMsg(res.message);
        //         this.getInitDataList()
        //         showMsg("成功")
        //         app.globalData.isTeamManager = false //role为1：单位管理员 role为2：消防安全员
        //         wx.setStorageSync('isTeamManager', false);
        //         let {
        //             tabList
        //         } = this.data
        //         tabList.splice(1, 1)
        //         this.setData({
        //             isTeamManager: false,
        //             tabList
        //         })
        //     })
        //     .catch(() => {});
    },
    // 设置岗位确定
    async roleConfirm(e) {
        console.log(e.detail.value.id);
        const res = await reqOrgTurnOver({
            orgId: app.globalData.orgId == 1 ? '' : app.globalData.orgId,
            userId: this.data.listItemInfo.userId,
            role: e.detail.value.id
        })
        if (res.code != 20000) {
            this.setData({
                showRole: false,
            })
            showMsg(res.message);
            return
        }
        this.setData({
            showRole: false,
            showMoreActions: false
        })
        this.getInitDataList()
        showMsg("设置成功")

        // 设置为管理员
        if (e.detail.value.id == 1) {
            app.globalData.isTeamManager = false //role为1：单位管理员 role为2：消防安全员
            wx.setStorageSync('isTeamManager', false);
            let {
                tabList
            } = this.data
            tabList.splice(1, 1)
            this.setData({
                isTeamManager: false,
                tabList
            })
        }

    },

    //----------- 审批列表开始
    // 弹出审批状态
    Clickstatus() {
        this.setData({
            showStatus: true
        })
    },
    // 隐藏审批状态
    statusClose() {
        this.setData({
            showStatus: false
        })
    },
    // 确定审批状态
    statusConfirm(e) {
        const {
            value,
        } = e.detail;
        this.setData({
            "statusApprove": value.id,
            "statusApproveText": value.text,
            showStatus: false,
        })
        this.getInitDataList1()
    },
    async getDataList1() {
        let params = {
            orgId: app.globalData.orgId == 1 ? '' : app.globalData.orgId,
            status: this.data.statusApprove,
        }
        const res = await reqOrgApprovalList(this.data.page1, 10, params)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        if (this.data.page1 === 1) {
            this.setData({
                dataList1: rows,
                isNextPage1: true
            })
        } else if (this.data.page1 > 1 && rows.length) {
            this.setData({
                dataList1: this.data.dataList1.concat(rows),
                isNextPage1: true
            })
        } else if (this.data.page1 > 1 && !rows.length) {
            showMsg('已经到底啦~')
            this.setData({
                isNextPage1: false
            })
        }
    },
    // 滚动到底部触发
    lower1() {
        if (!this.data.isNextPage1) return
        this.setData({
            page1: this.data.page1 + 1,
        })
        this.getDataList1()
    },
    // 下拉刷新
    async onRefresh1() {
        this.setData({
            dataList1: [],
            page1: 1,
            isNextPage1: true,
            triggered1: true,
        })
        await this.getDataList1()
        this.setData({
            triggered1: false,
        })
    },
    // 输入框搜索
    searchChange1(e) {
        this.data.searchValue1 = validateEmoji(e.detail.replace(/\s+/g, ''))
        this.setData({
            searchValue1: this.data.searchValue1,
            page1: 1,
            isNextPage1: true
        })
        clearTimeout(this.data.timer)
        this.data.timer = setTimeout(() => {
            this.getDataList1()
        }, 500)
    },
    // 操作列表后回到最初状态
    getInitDataList1() {
        this.setData({
            page1: 1,
            isNextPage1: true,
            dataList1: []
        })
        this.getDataList1()
    },
    clickApproval(e) {
        let {
            item
        } = e.currentTarget.dataset
        this.setData({
            listItemInfo1: item,
            showMoreActions1: true
        })
    },
    // 点击xx
    closeMoreActions1() {
        this.unShowMoreActions1()
    },
    // 隐藏更多操作弹窗
    unShowMoreActions1() {
        this.setData({
            showMoreActions1: false
        })
    },
    roleClose2() {
        this.setData({
            showRole2: false
        })
    },
    roleConfirm2(e) {
        // console.log(e);
        this.setData({
            showRole2: false,
        })
        let {
            listItemInfo1,
        } = this.data
        Dialog.confirm({
                title: '温馨提示',
                message: `此操作将通过成员${listItemInfo1.username}加入团队，是否继续？`,
            })
            .then(async () => {
                let params = {
                    id: listItemInfo1.id,
                    userId: app.globalData.userId,
                    status: 2,
                    tenantId: app.globalData.tenantId,
                    role: e.detail.value.id
                }
                const res = await reqOrgApprovalEdit(params)
                this.unShowMoreActions1()
                if (res.code != 20000) return showMsg(res.message);
                this.getInitDataList1()
                showMsg("成功")
            })
            .catch(() => {});
    },
    // 通过
    clickPass() {
        this.setData({
            showRole2: true,
        })
        return;
        let {
            listItemInfo1,
        } = this.data
        Dialog.confirm({
                title: '温馨提示',
                message: `此操作将通过成员${listItemInfo1.username}加入团队，是否继续？`,
            })
            .then(async () => {
                let params = {
                    id: listItemInfo1.id,
                    userId: app.globalData.userId,
                    status: 2,
                    tenantId: app.globalData.tenantId,
                }
                const res = await reqOrgApprovalEdit(params)
                this.unShowMoreActions1()
                if (res.code != 20000) return showMsg(res.message);
                this.getInitDataList1()
                showMsg("成功")
            })
            .catch(() => {});
    },
    // 拒绝
    clickRefuse() {
        let {
            listItemInfo1,
        } = this.data
        Dialog.confirm({
                title: '温馨提示',
                message: `此操作将拒绝成员${listItemInfo1.username}加入团队，是否继续？`,
            })
            .then(async () => {
                let params = {
                    id: listItemInfo1.id,
                    userId: app.globalData.userId,
                    status: 3,
                    tenantId: app.globalData.tenantId,
                }
                const res = await reqOrgApprovalEdit(params)
                this.unShowMoreActions1()
                if (res.code != 20000) return showMsg(res.message);
                this.getInitDataList1()
                showMsg("已拒绝")
            })
            .catch(() => {});
    },
    //----------- 审批列表结束
    // 邀请成员
    addClick() {
        wx.navigateTo({
            url: '/pages/personal-inside-page/team-add/team-add',
        })
    },
    // 退出团队
    async exitTeamClick() {
        // if (this.data.isTeamManager) {
        //     showMsg("您是管理员，请先移交管理员权限再退出此团队")
        //     return
        // }
        let isOnlyOrg = await this.getOrgList()
        if (isOnlyOrg) {
            // 1、如果有多个单位，去到单位列表
            Dialog.confirm({
                    title: '温馨提示',
                    message: `此操作将退出该机构，是否继续退出？`,
                })
                .then(async () => {
                    const res = await reqOrgExit({
                        orgId: app.globalData.orgId == 1 ? '' : app.globalData.orgId,
                        userId: app.globalData.userId,
                    })
                    if (res.code != 20000) return showMsg(res.message);
                    app.globalData.orgId = app.globalData.orgName = ''
                    wx.setStorageSync('orgId', '')
                    wx.setStorageSync('orgName', '')
                    wx.reLaunch({
                        url: '/pages/personal-inside-page/org/org',
                    })
                })
                .catch(() => {});
        } else {
            // 2、如果只剩下一个单位，退回登录
            Dialog.confirm({
                    title: '温馨提示',
                    message: `该机构是您存在的最后一个机构，是否继续？`,
                })
                .then(async () => {
                    const res = await reqOrgExit({
                        orgId: app.globalData.orgId == 1 ? '' : app.globalData.orgId,
                        userId: app.globalData.userId,
                    })
                    if (res.code != 20000) return showMsg(res.message);
                    this.exitLogin()
                })
                .catch(() => {});
        }

    },
    // 请求用户下存在单位数量
    async getOrgList() {
        let params = {
            tenantId: app.globalData.tenantId,
            userId: app.globalData.userId,
            roleName: app.globalData.rolename,
        }
        const res = await reqOrgList(this.data.page, 3, params)
        if (res.code !== 20000) return showMsg(res.message)
        if (res.data.rows.length > 1) {
            //如果用户下还存在两个或两个以上的单位，则去到单位列表选择一个单位
            return true
        } else {
            console.log("否则");
            // 否则提醒，退出将回到登录
            return false
        }
    },
    // 去详情
    goDetail(e) {
        return
        let {
            item
        } = e.currentTarget.dataset
        let info = JSON.stringify(item)
        wx.navigateTo({
            url: `/pages/personal-inside-page/team-detail/team-detail?item=${info}`,
        })
    },
    // 拨打电话号码
    makePhoneCall(e) {
        // console.log(e);
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.mobile //仅为示例，并非真实的电话号码
        })
    },
})